package fr.upmc.i3s.upmcontact.views.connection;

import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.parse.Parse;
import com.parse.ParseAnalytics;

import fr.upmc.i3s.upmcontact.R;
import fr.upmc.i3s.upmcontact.backend.BackEndBridge;
import fr.upmc.i3s.upmcontact.backend.BackEndBridgeImpl;
import fr.upmc.i3s.upmcontact.contents.User;
import fr.upmc.i3s.upmcontact.listeners.OnConnectionChangeListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class SignUpActivity extends Activity {
	
	private BackEndBridge backEndInstance;
	
	private ImageView ivConnectivity;
	private EditText etUserName;
	private EditText etPassword;
	private EditText etPasswordRepeat;
	private EditText etEmail;
	private Button bSignUp;
	private Button bSignIn;
	private TextView tvInformations;
	
	private OnConnectionChangeListener connectivityListener;
	private boolean listenerRegistered;
	
	
	  ////////////////////
	 // INITIALIZATION //
	////////////////////
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_signup);
		backEndInit();
		customizeActionBar();
		connectivityListener = new OnConnectionChangeListener(ivConnectivity, null);
		fetchViews();
		setListeners();
	}
	
	@Override 
	protected void onDestroy() {
		super.onDestroy();
		if(listenerRegistered) {
			unregisterReceiver(connectivityListener);
			listenerRegistered = false;
		}
	}
	
	private void customizeActionBar() {
		this.setTitle("");
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().setDisplayShowTitleEnabled(false);
		getActionBar().setDisplayUseLogoEnabled(false);
		getActionBar().setCustomView(R.layout.layout_action_bar);
		getActionBar().setDisplayShowCustomEnabled(true);
		TextView title = (TextView) findViewById(R.id.textView_title_activity);
		title.setText(getString(R.string.title_activity_signup));
		ImageView toggle = (ImageView) findViewById(R.id.imageView_toggle_menu);
		toggle.setVisibility(View.GONE);
		ivConnectivity = (ImageView) findViewById(R.id.imageView_connectivity);
	}
	
	private void backEndInit() {
		Parse.initialize(this, BackEndBridgeImpl.APPLICATION_ID, BackEndBridgeImpl.CLIENT_KEY);
		ParseAnalytics.trackAppOpened(getIntent());
		this.backEndInstance = BackEndBridgeImpl.getInstance(this);
		this.backEndInstance.reinitBackEnd(this);
	}
	
	private void fetchViews() {
		this.etUserName = (EditText) findViewById(R.id.editText_login);
		this.etPassword = (EditText) findViewById(R.id.editText_password);
		this.etPasswordRepeat = (EditText) findViewById(R.id.editText_repeat_password);
		this.etEmail = (EditText) findViewById(R.id.editText_email);
		this.bSignIn = (Button) findViewById(R.id.button_signIn);
		this.bSignUp = (Button) findViewById(R.id.button_signUp);
		this.tvInformations = (TextView) findViewById(R.id.textView_infos_signup);
	}
	
	private void setListeners() {
		this.bSignIn.setOnClickListener(onSignInClickListener); 			// Sign In button
		this.bSignUp.setOnClickListener(onSignUpClickListener); 			// Sign Up button
		this.etUserName.setOnTouchListener(onTouchListenerAdapter); 		// Username edittext
		this.etPassword.setOnTouchListener(onTouchListenerAdapter); 		// Password edittext
		this.etPasswordRepeat.setOnTouchListener(onTouchListenerAdapter); 	// Password repeat edittext
		this.etEmail.setOnTouchListener(onTouchListenerAdapter); 			// Email edittext
		registerReceiver(connectivityListener, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
		listenerRegistered = true;
	}

	
	  ///////////////
	 // LISTENERS //
	///////////////
	
	private OnClickListener onSignUpClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String username = etUserName.getText().toString();
			if(username == null || username.equals("") || username.equals(" ")) {
				etUserName.setHintTextColor(Color.RED);
				tvInformations.setText(R.string.error_wrong_login);
				tvInformations.setVisibility(View.VISIBLE);
				return;
			}
			String password = etPassword.getText().toString();
			if(password == null || password.equals("") || password.equals(" ")) {
				etPassword.setHintTextColor(Color.RED);
				tvInformations.setText(R.string.error_wrong_password);
				tvInformations.setVisibility(View.VISIBLE);
				return;
			}
			if(password.length() < 8) {
				etPassword.setText("");
				etPassword.setHintTextColor(Color.RED);
				tvInformations.setText(R.string.error_size_password);
				tvInformations.setVisibility(View.VISIBLE);
				return;
			}
			String repeatPassword = etPasswordRepeat.getText().toString();
			if(repeatPassword == null || repeatPassword.equals("") || repeatPassword.equals(" ")
					|| !password.equals(repeatPassword)) {
				etPasswordRepeat.setText("");
				etPasswordRepeat.setHintTextColor(Color.RED);
				tvInformations.setText(R.string.error_passwords_dont_match);
				tvInformations.setVisibility(View.VISIBLE);
				return;
			}
			String email = etEmail.getText().toString();
			if(email == null || email.equals("") || email.equals(" ")) {
				etEmail.setHintTextColor(Color.RED);
				tvInformations.setText(R.string.error_wrong_email);
				tvInformations.setVisibility(View.VISIBLE);
				return;
			}
			if(!isValidEmail(email)) {
				etEmail.setTextColor(Color.RED);
				etEmail.setHintTextColor(Color.RED);
				tvInformations.setText(R.string.error_invalid_email);
				tvInformations.setVisibility(View.VISIBLE);
				return;
			}
			User user = new User(null, null, null, username, password, email, false);
			backEndInstance.signup(user);
			// close keyboard :
			InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(etUserName.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(etPassword.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(etPasswordRepeat.getWindowToken(), 0);
			imm.hideSoftInputFromWindow(etEmail.getWindowToken(), 0);
		}
	};
	
	
	private OnClickListener onSignInClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(SignUpActivity.this, SignInActivity.class);
			startActivity(intent);
			finish();
		}
	};
	
	
	private OnTouchListener onTouchListenerAdapter = new OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent arg1) {
			Log.e("TAG", "COUCOU");
			if(view instanceof EditText) {
				EditText etView = (EditText) view;
				etView.setTextColor(Color.BLACK);
				tvInformations.setText("");
				tvInformations.setVisibility(View.GONE);
			}
			return false;
		}
	};

	
	private static boolean isValidEmail(String email) {
		Pattern p = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$");
		Matcher m = p.matcher(email.toUpperCase(Locale.getDefault()));
		return m.matches();
	}
	
	
	  ///////////////
	 // CALLBACKS //
	///////////////
	
	@Override
	public void onBackPressed() {
	    new AlertDialog.Builder(this)
	        .setTitle(R.string.really_cancel)
	        .setMessage(R.string.really_cancel_msg)
	        .setNegativeButton(android.R.string.no, null)
	        .setPositiveButton(android.R.string.yes, new android.content.DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface arg0, int arg1) {
	        		Intent intent = new Intent(SignUpActivity.this, SignInActivity.class);
	        		startActivity(intent);
	        		finish();
	            }
	        }).create().show();
	}
	
}
